<?php

function alipaySave($param, $type='notify') 
{
	include dirname(__FILE__).'/alipay_notify.php';
	include dirname(__FILE__).'/alipay_config.php';
	
	if ($type == 'notify') {
		$alipay = new alipay_notify($partner, $key, $sign_type, $_input_charset, $transport);    //构造通知函数信息
		$verify_result = $alipay->notify_verify();  //计算得出通知验证结果
		$trade_status = $_POST['trade_status'];
		$orderNo = $_POST['out_trade_no'];
		$channelOrderNo = $_POST['trade_no'];
	} else {
		$alipay = new alipay_notify($partner, $key, $sign_type, $_input_charset, $transport);
		$verify_result = $alipay->return_verify();
		$trade_status = $_GET['trade_status'];
		$orderNo = $_GET['out_trade_no'];
		$channelOrderNo = $_GET['trade_no'];
	}
	
	// 调试时注释下面判断,正式上线取消注释
	if (!$verify_result) {
		return false;
	}
	
	// 交易不成功,不做业务处理
    if($trade_status != 'TRADE_FINISHED' && $trade_status != 'TRADE_SUCCESS') { 
    	return false;
    }
	
	// 验证通过开始处理
	$model = M('pay_order_log');
	$record = $model->where(array('order_no'=>$orderNo))->find();
	// 支付成功已处理,不需要再处理了
	if ($record['status'] != 0) {
		return true;;
	}
	
	$now = time();
	
	$data = array(
		'status'			=> 2,
		'pay_time'			=> $now,
		'end_time'			=> $now,
		'channel_order_no'	=> $channelOrderNo,
	);
	$return  = $model->where('id='.$record['id'])->data($data)->save();
	if (!$return) {
		return false;
	}
	
	// 调用充值到游戏的公用接口,使充值到游戏当中
	if ($record['target'] == 1) {
		$thinkphp = dirname(dirname(dirname(dirname(__FILE__)))).'/ThinkPHP/';
		include_once $thinkphp.'Extend/UserDefined/PayToGame.class.php';
		$return = PayToGame::pay($record);
		$payGameStatus = PayToGame::$pay_game_status;
		// 充值游戏成功了,按正常标志订单完成充值,否则只标志未充值到游戏,计划任务重新充值到游戏中去
		if ($return) {
			$status = 2;
		} else {
			$status = 1;
		}
		$data = array(
			'status'			=> $status,
			'pay_game_status'	=> $payGameStatus,
		);
		$return  = $model->where('id='.$record['id'])->data($data)->save();
// 		if (!$return) {
// 			return false;
// 		}
	} else {//充值到平台,只增加平台币,调用用户增加平台币接口
		$addCoin = $record['fact_value'];//添加的平台币
		$addCredit = $record['pay_money'] * C('PAY_GET_CREDIT_RATE');//添加的积分
		User::addCoin($record['uid'], $addCoin, 0, 0, $orderNo);
	}
	// 充值成功添加积分
	User::addCredit($record['uid'], $addCredit);
	
	// 最近充值游戏记录
	$where = 'uid='.$record['uid'].' and game_id='.$record['game_id'];
	$lastPay = M('last_pay_game_log');
	$lastRecord = $lastPay->where($where)->find();
	if ($lastRecord) {
		$data = array(
			'last_pay_time'	=> time()
		);
		$lastPay->where('id='.$lastRecord['id'])->data($data)->save();
	} else {
		$data = array(
			'uid'			=> $record['uid'],
			'game_id'		=> $record['game_id'],
			'last_pay_time'	=> time()
		);
		$lastPay->where('id='.$lastRecord['id'])->data($data)->add();
	}
	
	return true;
}